package com.my.ads.lib.service;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.my.ads.lib.AdSummary;
import com.my.ads.lib.listen.LockScreenReceiver;

/**
 * Created by xuanyang on 2018/3/6.
 */

public class KeepService extends Service {


    private final static int SERVICE_STA_ID = -0x1001;
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LockScreenService.mReceiver = new LockScreenReceiver();
        if (Build.VERSION.SDK_INT < 25) {
            startService(new Intent(this, StaInnerService.class));
            startForeground(SERVICE_STA_ID, new Notification());
        }
        if (LockScreenService.mReceiver == null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_POWER_CONNECTED);
            filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
            filter.addAction(Intent.ACTION_BATTERY_LOW);
            filter.addAction(Intent.ACTION_BATTERY_OKAY);
            try {
                registerReceiver(LockScreenService.mReceiver, filter);
            } catch (Exception e) {
            }
        }




        try {
            AdSummary.getInstance().cacheAllAd(this, "0", "1");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //守护 Service 组件的启用状态, 使其不被 MAT 等工具禁用
        try {
            getPackageManager().setComponentEnabledSetting(new ComponentName(getPackageName(), KeepService.class.getName()),
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
        } catch (Exception e) {}

        return START_STICKY;


    }

    public static class StaInnerService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            startForeground(SERVICE_STA_ID, new Notification());
            stopSelf();

            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent intent) {
            throw new UnsupportedOperationException("Not yet implemented");
        }


    }

}
